﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Security.Claims;
using WebAPITest.Models.Database;

namespace WebAPITest.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CacheController : ControllerBase
    {
        private readonly IMemoryCache cache;
        private readonly WebEnterpriseIIContext _db;
        /// <summary>
        /// 构造注入 从IOC容器取出 缓存服务
        /// </summary>
        /// <param name="cache"></param>
        public CacheController(IMemoryCache cache, WebEnterpriseIIContext db)
        {
            this.cache = cache;
            _db = db;
            //1:key / value
            //2:key是字符串 缓存数据的名字
            //3：value 可以是任何的类型 string int byte list object class
        }

        /// <summary>
        /// 判断缓存是否存在
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<string> TryGetValueCache()
        {
            
            if (cache.TryGetValue("UserName", out string username))
            {
                return "该缓存存在" + username;
            }
            else
            {
                return "该缓存不存在";
            }
        }
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<string> SetCache()
        {
            return cache.Set("UserName", "liudacheng");
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<string> GetCache()
        {
            return cache.Get<string>("UserName");
        }

        [HttpGet]
        public ActionResult<string> RemoveCache()
        {
            cache.Remove("UserName");
            return "删除缓存成功";
        }


        [HttpGet]
        public ActionResult<string> CacheTime1()
        {
            string msg = string.Empty;
            //设置缓存 永不过期
            cache.Set("UserName", "admin");
            // 读取缓存
            for (int i = 1; i <= 5; i++)
            {
                //每一次循环读取一次缓存
                msg += $"第{i}秒缓存值：{cache.Get<string>("UserName")}\n";
                //睡眠一秒
                Thread.Sleep(1000);
            }

            // 返回
            return msg;
        }

    
        [HttpGet]
        public ActionResult<string> CacheTime2()
        {
            string msg = string.Empty;
            //设置缓存 指定3秒后过期
            cache.Set("UserName", "admin", TimeSpan.FromSeconds(3));

            // 读取缓存
            for (int i = 1; i <= 5; i++)
            {
                msg += $"第{i}秒缓存值：{cache.Get<string>("UserName")}\n";
                Thread.Sleep(1000);
            }

            // 返回
            return msg;
        }

      
        [HttpGet]
        public ActionResult<string> CacheTime3()
        {
            string msg = string.Empty;
            
            cache.Set("UserName", "admin", new MemoryCacheEntryOptions
            {
               
                SlidingExpiration = TimeSpan.FromSeconds(0.5)
            });

            // 读取缓存
            for (int i = 1; i <= 5; i++)
            {

                msg += $"第{i}秒缓存值：{cache.Get<string>("UserName")}\n";
                Thread.Sleep(1000);
            }

            // 返回
            return msg;
        }

      
        [HttpGet]
        public ActionResult<string> Get()
        {
            string msg = string.Empty;
           
            cache.Set("UserName", "admin", new MemoryCacheEntryOptions
            {
                
                SlidingExpiration = TimeSpan.FromSeconds(0.5),
                //绝对时间 3秒后 必定过期
                AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(3)
            });

            // 读取缓存
            for (int i = 1; i <= 5; i++)
            {
                msg += $"第{i}秒缓存值：{cache.Get<string>("UserName")}\n";
                Thread.Sleep(1000);
            }

            // 返回
            return msg;
        }
        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public List<Good> GetGoodList()
        {
           
            if (cache.TryGetValue("GoodCache", out List<Good> goodList))
            {
                //3、如果有则直接返回缓存数据
                return goodList;
            }
            else
            {
                
                var goods = _db.Goods.ToList();
                cache.Set("GoodCache", goods, TimeSpan.FromMinutes(30));
                return goods;
            }
        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <param name="goodId"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public Good GetGoodInfo(int goodId)
        {
            //商品详情
            var good = _db.Goods.FirstOrDefault(x => x.Id == goodId);

            
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            
            var record = cache.Get<List<Good>>($"UserViews{userId}");
            //浏览商品记录
            var views = new List<Good>();
            views.Add(good); 

          
            if (record != null)
                views.AddRange(record); 

            cache.Set($"UserViews{userId}", views);
            return good;
        }

        //对象的序列化 和 反序列化
    }
}
